from django.core.management.base import BaseCommand
from apps.OMM.models import Order
import logging

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = '更新所有已激活订单的提成计算'

    def add_arguments(self, parser):
        parser.add_argument(
            '--order-id',
            type=int,
            help='指定单个订单ID进行更新',
        )

    def handle(self, *args, **options):
        order_id = options.get('order_id')
        
        if order_id:
            try:
                orders = Order.objects.filter(id=order_id)
                if not orders.exists():
                    self.stdout.write(self.style.ERROR(f'未找到ID为 {order_id} 的订单'))
                    return
                self.stdout.write(self.style.SUCCESS(f'将更新ID为 {order_id} 的订单'))
            except Exception as e:
                self.stdout.write(self.style.ERROR(f'查询订单时出错: {str(e)}'))
                return
        else:
            # 获取所有已激活的订单
            orders = Order.objects.filter(order_status=1)
            self.stdout.write(self.style.SUCCESS(f'找到 {orders.count()} 个已激活订单需要更新'))
        
        updated_count = 0
        error_count = 0
        
        for order in orders:
            try:
                # 获取产品的提成分类比例
                product = order.product_name
                if product:
                    commission_ratio = product.commission_category.commission_ratio
                    order_amount = order.order_amount
                    
                    if order_amount:
                        # 计算提成
                        commission = order_amount * commission_ratio
                        # 检查是否双倍提成
                        if order.is_double_coms == 1:
                            commission *= 2
                        
                        # 更新订单的提成字段
                        old_commission = order.commission
                        order.commission = commission
                        order.save(update_fields=['commission'])
                        
                        self.stdout.write(
                            self.style.SUCCESS(
                                f'订单 #{order.id} ({order.order_number}): 提成从 {old_commission} 更新为 {commission}'
                            )
                        )
                        updated_count += 1
                    else:
                        self.stdout.write(
                            self.style.WARNING(f'订单 #{order.id} ({order.order_number}): 订单金额为空，跳过')
                        )
                else:
                    self.stdout.write(
                        self.style.WARNING(f'订单 #{order.id} ({order.order_number}): 产品为空，跳过')
                    )
            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(f'更新订单 #{order.id} ({order.order_number}) 时出错: {str(e)}')
                )
                error_count += 1
        
        self.stdout.write(
            self.style.SUCCESS(
                f'更新完成: 成功 {updated_count} 个, 失败 {error_count} 个'
            )
        ) 